<template>
	<view class="shopping-card">
		<!-- 购物车 -->
		<u-navbar leftIconSize="34rpx" autoBack :placeholder="true" bgColor="#ffffff">
			<view class="" slot="center">
				<text class="c-000 pf-sc fw-600" style="font-size: 34rpx">购物车</text>
			</view>
		</u-navbar>
		<!--  -->
		<view
			class="set-data-container w-750 b-box d-flex flex-c ali-i-c just-sw po-re"
			style="background: #f0f1f5"
			:style="{ height: containerHeight }"
		>
			<view scroll-y="true" :style="{ height: parseInt(containerHeight) - 49 + 'px' }">
				<scroll-view class="w-750 b-box" style="padding-bottom: 20rpx" v-if="dataList.length > 0">
					<view class="shop-card" style="margin-top: 20rpx" v-for="item of dataList" :key="item.id">
						<!-- 购物车商品卡片 -->
						<view
							class="w-750 b-box d-flex felx-r ali-i-c just-sw bg-ff"
							style="height: 320rpx; padding: 32rpx"
						>
							<view class="d-flex flex-r ali-i-c just-c">
								<view
									v-if="!item.isSelected"
									@click="Selected(item)"
									style="
                    width: 36rpx;
                    height: 36rpx;
                    border: 4rpx solid #dddddd;
                    border-radius: 150rpx;
                  "
								></view>
								<view v-else @click="Selected(item)" style="width: 42rpx; height: 42rpx">
									<image
										:src="require('../static/xz.png')"
										style="width: 42rpx; height: 42rpx"
									></image>
								</view>
							</view>
							<view class="d-flex flex-r ali-i-c just-s" style="height: inherit; width: 600rpx">
								<view
									class="d-flex flex-r ali-i-c just-c"
									style="
                    width: 200rpx;
                    height: 200rpx;
                    border-radius: 10rpx;
                    overflow: hidden;
                    margin-right: 20rpx;
                  "
									@click="bigImg(item)"
								>
									<image :src="item.image" style="width: 200rpx; height: 200rpx"></image>
								</view>
								<view
									class="d-flex flex-c ali-i-s just-s b-box po-re"
									style="
                    height: inherit;
                    padding: 32rpx 0;
                    left: 10rpx;
                    flex: 1;
                  "
								>
									<text class="pf-sc fw-500 c-333" style="font-size: 28rpx; margin-bottom: 10rpx">
										{{ item.name }}
									</text>
									<view
										class="d-flex flex-r ali-i-c just-c"
										style="
                      width: 360rpx;
                      height: 46rpx;
                      margin-bottom: 48rpx;
                      background-color: #f5f5f5;
                      border-radius: 76rpx;
                    "
									>
										<text style="font-size: 24rpx; color: #666666" class="pf-sc fw-400">
											{{ item.guige.name }}
										</text>
									</view>
									<view class="d-flex flex-r ali-s-c just-sw w-100" style="height: 60rpx">
										<view class="d-flex flex-r ali-i-c just-s">
											<text
												class="fw-600 pf-sc po-re"
												style="
                          font-size: 22rpx;
                          color: #ff5c00;
                          top: 4rpx;
                          margin-right: 4rpx;
                        "
											>
												¥
											</text>
											<text class="fw-600 pf-sc" style="font-size: 36rpx; color: #ff5c00">
												{{ item.guige.lsprice == null ? 0 : item.guige.lsprice}}
											</text>
										</view>
										<view>
											<u-number-box :min="1" :max="100">
												<view slot="minus" style="width: 60rpx; height: 60rpx" @click="Minus(item)">
													<image
														v-if="item.num > 1"
														:src="require('../static/icon1.png')"
														style="width: 60rpx; height: 60rpx"
													></image>
													<image
														v-else
														:src="require('../static/icon3.png')"
														style="width: 60rpx; height: 60rpx"
													></image>
												</view>
												<view
													slot="input"
													style="width: 60rpx; height: 60rpx"
													class="d-flex flex-r ali-i-c just-c"
												>
													<text class="pf-sc fw-600" style="font-size: 30; color: #666666">
														{{ item.num }}
													</text>
												</view>
												<view slot="plus" @click="Plus(item)" style="width: 60rpx; height: 60rpx">
													<image
														:src="require('../static/icon2.png')"
														style="width: 60rpx; height: 60rpx"
													></image>
												</view>
											</u-number-box>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view
				class="w-750 b-box bg-ff d-flex flex-r ali-i-c just-sw"
				style="height: 98rpx; padding: 0 36rpx 0 32rpx;position: fixed;bottom: 0;"
			>
				<view class="d-flex flex-r ali-i-c just-c">
					<view
						v-if="!ACTIVEGOODSALL_"
						@click="SelectedAll"
						style="
              width: 36rpx;
              height: 36rpx;
              border: 4rpx solid #dddddd;
              border-radius: 150rpx;
            "
					></view>
					<view v-else @click="SelectedAll" style="width: 42rpx; height: 42rpx">
						<image :src="require('../static/xz.png')" style="width: 42rpx; height: 42rpx"></image>
					</view>
				</view>
				<view class="d-flex flex-r ali-i-c just-e">
					<view class="d-flex flex-r ali-i-c just-s">
						<text>合计:</text>
						<view class="d-flex flex-r ali-i-c just-s" style="margin-right: 16rpx">
							<text
								class="fw-600 pf-sc po-re"
								style="
                  font-size: 22rpx;
                  color: #ff5c00;
                  top: 4rpx;
                  margin-right: 4rpx;
                "
							>
								¥
							</text>
							<text class="fw-600 pf-sc" style="font-size: 36rpx; color: #ff5c00">{{ total }}</text>
						</view>
					</view>
					<view class="d-flex">
						<!-- 删除 -->
						<u-button
							:throttleTime="700"
							@click="deleteCars"
							:customStyle="{
								height: '74rpx',
								width: '196rpx',
								font: '400 32rpx PingFang SC',
								color: '#ffffff',
								borderWidth: '0rpx',
								background: 'linear-gradient(180deg, #4885C5 0%, #3B52A6 100%)',
								borderRadius: '44rpx'
							}"
							shape="square"
							text="移除商品"
						></u-button>

						<u-button
							:throttleTime="700"
							@click="open"
							:customStyle="{
								height: '74rpx',
								width: '196rpx',
								font: '400 32rpx PingFang SC',
								color: '#ffffff',
								borderWidth: '0rpx',
								background: 'linear-gradient(180deg, #4885C5 0%, #3B52A6 100%)',
								borderRadius: '44rpx'
							}"
							shape="square"
							:text="`立即结算${SelectCount > 0 ? `(${SelectCount})` : ''}`"
						></u-button>
					</view>
				</view>
			</view>
		</view>

		<!-- popup -->
		<u-popup
			:show="show"
			mode="bottom"
			overlayOpacity="0.6"
			:round="25"
			@close="close"
			@open="open"
		>
			<view class=" d-flex flex-c ali-i-s just-s b-box" style="padding: 40rpx 0;">
				<!-- title -->
				<view class="d-flex flex-r ali-i-c just-c w-100 b-box po-re">
					<text class="fw-500 pf-sc fw-500" style="font-size: 32rpx;">选择支付方式</text>
					<text
						class="fw-500 pf-sc fw-500 po-ab"
						style="font-size: 32rpx; right:42rpx"
						@click="close"
					>
						×
					</text>
				</view>
				<!--  -->
				<view
					class=" d-flex flex-r ali-i-c just-sw w-100 b-box"
					@click="Select = 2"
					style="height: 120rpx;border-bottom: 2rpx solid #dedede;padding: 0 36rpx 0 32rpx;"
				>
					<view class="d-flex flex-r ali-i-c just-s">
						<image
							:src="require('.././static/hy2.png')"
							style="width: 56rpx;height: 56rpx;margin-right: 16rpx;"
						></image>
						<text class="fw-400 pf-sc c-333" style="font-size: 30rpx;">余额支付</text>
						<text class="fw-400 pf-sc c-333" style="font-size: 30rpx;">（￥{{ user.money }}）</text>
					</view>
					<view v-if="Select === 2">
						<image :src="require('.././static/xz.png')" style="width: 36rpx;height: 36rpx;"></image>
					</view>
				</view>
				<view
					class=" d-flex flex-r ali-i-c just-sw w-100 b-box"
					@click="Select = 1"
					style="height: 120rpx;border-bottom: 2rpx solid #dedede;margin-bottom: 60rpx;padding: 0 36rpx 0 32rpx;"
				>
					<view class="d-flex flex-r ali-i-c just-s">
						<image
							:src="require('.././static/hy3.png')"
							style="width: 56rpx;height: 56rpx;margin-right: 16rpx;"
						></image>
						<text class="fw-400 pf-sc c-333" style="font-size: 30rpx;">微信支付</text>
						<!-- <text class="fw-400 pf-sc c-333" style="font-size: 30rpx;">（2次可用）</text> -->
					</view>
					<view v-if="Select === 1">
						<image :src="require('.././static/xz.png')" style="width: 36rpx;height: 36rpx;"></image>
					</view>
				</view>
				<!-- btn -->
				<view class="d-flex flex-r ali-i-c just-c w-100 b-box" style="margin-bottom: 12rpx;">
					<u-button
						@click="SubmitOrder"
						:customStyle="{
							height: '88rpx',
							width: '670rpx',
							font: '500 32rpx PingFang SC',
							color: '#ffffff',
							borderWidth: '0rpx',
							background: 'linear-gradient(180deg, #4885C5 0%, #3B52A6 100%)',
							borderRadius: '44rpx'
						}"
						shape="square"
						text="确定"
					></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { _containerHeight } from '@/utils/GetSys.js';
import { carlist, carbuy1, address, carbuynow, editcar } from '@/common/api.js';
import uNumberBox from '../components/uview-ui/components/u-number-box/u-number-box';
import Unavbar from '../components/uview-ui/components/u-navbar/u-navbar';
import uButton from '../components/uview-ui/components/u-button/u-button';
export default {
	components: {
		'u-navbar': Unavbar,
		'u-button': uButton,
		'u-number-box': uNumberBox
	},
	data() {
		return {
			user: uni.getStorageSync('userInfo'), //获取当前用户的信息
			show: false,
			Select: '',
			containerHeight: '',
			dataList: [],
			SelectCount: 0, //当前选中商品数量
			ACTIVEGOODSALL_: false, //是否全选
			total: 0,
			carid: [], //购物车的id
			addressList: ''
		};
	},
	watch: {
		dataList: {
			handler(newVal, oldVal) {
				this.total = 0;
				this.SelectCount = 0;
				// console.log(newVal);
				if (newVal.length > 0) {
					// 计算价格
					newVal.forEach((shopItem, shopIndex) => {
						if (shopItem.isSelected === true) {
							this.total += shopItem.price * shopItem.num;
							this.SelectCount += 1;
						}
					});
					let res = newVal.every(item => item.isSelected === true);
					if (res) {
						this.ACTIVEGOODSALL_ = true;
					} else {
						this.ACTIVEGOODSALL_ = false;
					}
				} else {
					this.ACTIVEGOODSALL_ = false;
				}
			},
			deep: true
		}
	},
	methods: {
		open() {
			for (var i = 0; i < this.dataList.length; i++) {
				if (this.dataList[i].isSelected == true && this.carid.indexOf(this.dataList[i].id) === -1) {
					this.carid.push(this.dataList[i].id);
				}
				if (!this.dataList[i].isSelected) {
					this.carid.splice(i, 1);
				}
			}
			if (this.carid.length == 0) {
				return uni.showToast({
					title: '请选择你要购买商品',
					icon: 'none'
				});
			}
			this.show = true;
		},
		close() {
			this.show = false;
		},

		bigImg(item) {
			item.isSelected = !item.isSelected;
			console.log(item);
		},
		//页面加载时获取当前用户的地址列表
		getAddress() {
			let params = {
				token: uni.getStorageSync('usertoken'),
				type: 5
			};
			address(params).then(res => {
				this.addressList = res.data.data;
				console.log(this.addressList);
			});
		},

		//我的购物车数据
		carList() {
			let params = {
				token: uni.getStorageSync('usertoken')
			};
			carlist(params).then(res => {
				console.log(res);
				if (res.data.code === 1) {
					let arr = res.data.data;
					//遍历数组为每个添加isSelected: false,属性用于复选框
					for (var i = 0; i < arr.length; i++) {
						arr[i]['isSelected'] = false;
					}
					this.dataList = res.data.data;
				}
			});
		},
		SubmitOrder() {
			//结算

			for (var i = 0; i < this.dataList.length; i++) {
				if (this.dataList[i].isSelected == true && this.carid.indexOf(this.dataList[i].id) === -1) {
					this.carid.push(this.dataList[i].id);
				}
				if (!this.dataList[i].isSelected) {
					this.carid.splice(i, 1);
				}
			}

			if (this.Select != 1 && this.Select != 2) {
				return uni.showToast({
					title: '请选择付款方式',
					icon: 'none'
				});
			}
      if(this.total===0){
				return uni.showToast({
					title:'支付金额不得为0',
					icon:'none'
				})
			}
			let params = {
				token: uni.getStorageSync('usertoken'),
				carids: this.carid.join(',') //这里就是购物车的id
			};
			carbuy1(params).then(res => {
				console.log(res);
				//如果计算成功 在购买商品
				if (res.data.code === 1) {
					let params = {
						token: uni.getStorageSync('usertoken'), //用户的token
						carids: this.carid.join(','), //购物车id
						paytype: this.Select, //支付方式
						aid: this.addressList[0].id //默认的地址id
					};

					//如果等于2用余额支付
					if (this.Select == 2) {
						carbuynow(params).then(res => {
							console.log(res);
							if (res.data.code === 1) {
								uni.showToast({
									title: '购买成功'
								});
								this.show = false;
								this.carList();
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}
						});
					}

					//等于1用微信支付
					//如果等于2用余额支付
					if (this.Select == 1) {
						carbuynow(params).then(res => {
							console.log(res);
							if (res.data.code == 1) {
								var paydata = res.data.data;
								uni.requestPayment({
									provider: 'wxpay',
									// "orderInfo": {  },
									// "appid":paydata.appId,  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
									nonceStr: paydata.nonceStr, // 随机字符串
									package: paydata.package, // 固定值
									partnerid: '1629006880', // 微信支付商户号
									prepayid: this.id, // 统一下单订单号
									timeStamp: paydata.timeStamp, // 时间戳（单位：秒）
									paySign: paydata.paySign, // 签名，这里用的 MD5/RSA 签名
									signType: paydata.signType, // 签名算法
									success(res) {
										//跳转到用户订单
										uni.showToast({
											title: '购买成功'
										});
										this.carList();
										this.show = false;
									},
									fail(e) {
										console.log(e);
										uni.showToast({
											title: e,
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}
						});
					}
				} else {
					return uni.showToast({
						title: res.data.msg,
						icon: 'none'
					});
				}
			});
		},
		//删除购物车
		deleteCars() {
			for (var i = 0; i < this.dataList.length; i++) {
				if (this.dataList[i].isSelected == true && this.carid.indexOf(this.dataList[i].id) === -1) {
					this.carid.push(this.dataList[i].id);
				}
				if (!this.dataList[i].isSelected) {
					this.carid.splice(i, 1);
				}
			}
			console.log(this.carid, '哈哈哈');

			let params = {
				token: uni.getStorageSync('usertoken'), //用户的token
				type: 2,
				ids: this.carid.join(',') //购物车id
			};
			editcar(params).then(res => {
				if (res.data.code === 1) {
					this.carList();
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					this.carList();
				} else {
					uni.showToast({
						title: '请选择你要删除的商品',
						icon: 'none'
					});
				}
			});
		},
		SelectedAll() {
			//全选
			if (this.ACTIVEGOODSALL_) {
				this.dataList.forEach(item => {
					item.isSelected = false;
				});
			} else {
				this.dataList.forEach(item => {
					item.isSelected = true;
				});
			}
		},
		Selected(item) {
			if (item.isSelected) {
				item.isSelected = false;
			} else {
				item.isSelected = true;
			}
		},
		Minus(item) {
			console.log(item.gid);
			if (item.num <= 1) {
				item.num = 1;
				return;
			}
			item.num--;
			//执行购物车更新请求
			let params = {
				token: uni.getStorageSync('usertoken'), //用户的token
				id: item.id,
				num: item.num,
				type: 1
			};
			editcar(params).then(res => {
				console.log(res);
			});
		},
		Plus(item) {
			console.log(item);
			item.num++;
			//执行购物车更新请求
			let params = {
				token: uni.getStorageSync('usertoken'), //用户的token
				id: item.id,
				num: item.num,
				type: 1
			};
			editcar(params).then(res => {
				console.log(res);
			});
		}
	},
	onLoad() {
		this.containerHeight = _containerHeight();
		this.carList();
		this.getAddress();
	}
};
</script>

<style lang="scss">
.shop-card:last-child {
	padding-bottom: 50rpx;
}
</style>
